/* 扫码率报表
 * @Author: liaoxin
 * @email: 2858765077@qq.com
 * @FilePath: \personnelmanage\src\pages\QuotaManage\Report\ScanRateReport\index.tsx
 * @Date: 2022-09-01 11:03:15
 * @LastEditTime: 2022-10-13 12:05:23
 */
/* eslint-disable array-callback-return */
import React from 'react'
import {
  BaseListPage,
  http,
  IBaseListPageState,
  IBaseListPageProps,
  IUdFormItem,
  UdMonthRangePicker
} from '@/lib'

import { Spin, TreeSelect } from 'antd'
import udMainStore from '@/store/UdMain'
import UdSelect from '@/components/UdFormControls/UdSelect'
import apis from '@/apis'
import quotaApis from '@/apis/AboutQuota'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import _ from 'lodash'
import moment from 'moment'
import 'moment/locale/zh-cn.js'
moment.locale('zh-cn')

const { TreeNode } = TreeSelect
export default class ScanRateReportList extends BaseListPage<IProps, IState> {
  protected useConditionsField = true
  private spanUI: any = {
    color: '#00c1de',
    fontWeight: 'bold',
    cursor: 'pointer',
    paddingRight: '10px',
    padding: '10px 0',
  }
  public columns: any[] = [
    ['序号', 'id', (text, record, index) => index + 1, { minWidth: '30px' }],
    { title: '品牌公司', dataIndex: 'brandName', minWidth: '60px' },
    { title: '所属片区', dataIndex: 'belongAreaName', minWidth: '60px' },
    { title: '经销商名称', dataIndex: 'dealerName', minWidth: '180px' },
    { title: '物料名称', dataIndex: 'matName', minWidth: '180px' },
    { title: '当日库存', dataIndex: 'todayStock', minWidth: '180px' },
  ]
  public brandList = udMainStore.brandList
  constructor(props: IProps) {
    super(props)
    this.state = {
      title: '扫码率报表',
      queryApi: params => {
        //统计月份  初始值会出现 startDate|endDate 的情况
        if (params.conditions['startDate|endDate']) {
          let ObjTime = Object.keys(params.conditions)
          let time = []
          let str = ''
          for (const item of ObjTime) {
            if (Array.isArray(params.conditions[item])) {
              str = item
              time = params.conditions[item]
            }
          }
          if (time && time.length > 0) {
            params.conditions.startDate = moment(time[0]).format('YYYY-MM') + '-01 00:00:00'
            params.conditions.endDate = moment(time[1]).endOf('month').format('YYYY-MM-DD') + ' 23:59:59'
          }
          params.conditions = _.omit(params.conditions, [str]);
        } else {
          let {
            conditions: { startDate, endDate },
          } = params
          startDate && (params.conditions.startDate = moment(startDate).format('YYYY-MM') + '-01 00:00:00')
          endDate && (params.conditions.endDate = moment(endDate).endOf('month').format('YYYY-MM-DD') + ' 23:59:59')
        }
        return http.post(quotaApis.getScanRatePage, params)
      },
      method: 'POST',
      rowKey: (record, index) => index + '',
      conditions: [
        {
          label: '品牌公司',
          id: 'brandCode',
          initialValue: this.brandList[0].value,
          render: (
            <UdSelect
              showSearch
              allowClear={false}
              options={this.brandList}
              onChange={value => {
                this.changeBrandCode(value)
              }}
            />
          ),
        },
        {
          label: '统计月份',
          id: ['startDate', 'endDate'],
          initialValue: [moment(), moment()],
          render: <UdMonthRangePicker />,
        },
        {
          label: '所属组织',
          id: 'belongAreaCode',
          render: () => (
            <TreeSelect showSearch treeNodeFilterProp="title">
              {this.mapTree(this.state.treeDataList)}
            </TreeSelect>
          ),
        },
        { label: '物料编号', id: 'prodBarcode' },
        { label: '物料名称', id: 'matName' },
        { label: '经销商编码', id: 'dealerCode' },
        { label: '经销商名称', id: 'dealerName' },
      ],
      columns: [],
      dataSource: [],
      uploading: false,
      downloading: false,
      tableProps: {
        scroll: { x: true },
      },
      prodBarCodeList: [],//配额列表
      treeDataList: [],//片区列表
      loading: true,
      useColumnCustomize: true,
    }
  }


  render() {
    this.state.dataSource.map(item => {
      if (item.movingMap.length > 0) {
        item.movingMap.map((obj: any, index: any) => {
          let keyList = Object.keys(obj)

          keyList.map(key => {
            item[`${key + index}`] = obj[`${key}`]
          })
        })

      }
    })
    let columns = [
      ['序号', 'id', (text, record, index) => index + 1, { minWidth: '20px' }],
      { title: '品牌公司', dataIndex: 'brandName', minWidth: '60px' },
      { title: '所属片区', dataIndex: 'belongAreaName', minWidth: '60px' },
      { title: '经销商名称', dataIndex: 'dealerName', minWidth: '180px' },
      { title: '经销商编码', dataIndex: 'dealerCode', minWidth: '180px' },
      { title: '经销商地址', dataIndex: 'address', minWidth: '180px' },
      { title: '物料名称', dataIndex: 'matName', minWidth: '180px' },
      { title: '物料编码', dataIndex: 'prodBarcode', minWidth: '180px' },
      { title: '当日库存', dataIndex: 'todayStock', minWidth: '180px' },
    ]
    if (this.state.dataSource.length > 0) {
      let monthArr = this.HandleDataSource(this.state.dataSource)
      columns.push(...monthArr)
    }
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '请求中，请稍后...'}
      >
        {
          super.render({
            columns,
            dataSource: this.state.dataSource
          })
        }
      </Spin>
    )
  }

  componentDidMount() {
    super.componentDidMount()
    this.changeBrandCode(this.filterForm.getFieldValue('brandCode'))
  }

  protected HandleDataSource = (dataSource: any[]) => {
    let monthArr = []
    for (let index = 0; index < dataSource[0].movingMap.length; index++) {
      let obj = dataSource[0]
      monthArr.push(
        {
          title: `${moment(obj[`${'create_time' + index}`]).format('YYYY年MM月')}`,
          dataIndex: `${index}`,
          minWidth: '180px',
          children: [
            {
              title: '动销数',
              align: 'center',
              dataIndex: `${'nowMove' + index}`,
              key: `${'nowMove' + index}`,
              width: 110,
            },
            {
              title: '入库箱码类型',
              align: 'center',
              dataIndex: `${'inboxType' + index}`,
              key: `${'inboxType' + index}`,
              width: 110,
              render: (text) => {
                return text === '1' ? '瓶' : (text === '0' ? '箱' : text)
              },
            },
            {
              title: '入库扫码数量',
              align: 'center',
              dataIndex: `${'inscanNum' + index}`,
              key: `${'inscanNum' + index}`,
              width: 110,
            },
            {
              title: '出库箱码类型',
              align: 'center',
              dataIndex: `${'ouboxType' + index}`,
              key: `${'ouboxType' + index}`,
              width: 110,
              render: (text) => {
                return text === '1' ? '瓶' : (text === '0' ? '箱' : text)
              },
            },
            {
              title: '出库数量',
              align: 'center',
              dataIndex: `${'ouscanNum' + index}`,
              key: `${'ouscanNum' + index}`,
              width: 110,
            },
            {
              title: '扫码数',
              align: 'center',
              dataIndex: `${'dscanNum' + index}`,
              key: `${'dscanNum' + index}`,
              width: 110,
            },
            {
              title: '扫码率',
              align: 'center',
              dataIndex: `${'rate' + index}`,
              key: `${'rate' + index}`,
              width: 110,
              render: (text) => {
                if (text !== '-') {
                  text = Number(text) * 100 + '%'
                }
                return text
              },
            },
          ]
        }
      )
    }
    return monthArr
  }

  protected filterReset = (form: WrappedFormUtils) => {
    let defaultValues: any = {}
    _.forEach(this.state.conditions, (item: IUdFormItem) => {
      if (item.initialValue) {
        let key = _.isArray(item.id) ? item.id.join('|') : item.id
        defaultValues[key] = item.initialValue
      }
    })
    var conditions = _.merge({}, this.defaultQueryParams.conditions, defaultValues)
    this.handleSearch(conditions)
    this.changeBrandCode(this.brandList[0].value)
  }


  private getProdBarList = (value: any) => {
    return http
      .get(quotaApis.getProdBarList, {
        params: { brandCode: value },
      })
      .then(res => {
        const { data = [] } = res
        const prodBarCodeList = data.map(item => ({ value: item.code, title: item.name }))
        return prodBarCodeList
      })
  }

  private changeBrandCode = (value: any) => {
    this.filterForm.setFieldsValue({ groupCode: undefined, belongAreaCode: undefined }, () => {
      this.setState({ prodBarCodeList: [], treeDataList: [] }, () => {
        Promise.allSettled([this.getProdBarList(value), this.getAreaList(value)]).then((res: any) => {
          this.setState({
            prodBarCodeList: res[0]?.value || [],
            treeDataList: res[1]?.value || [],
          })
        })
      })
    })
  }

  private getAreaList = (value: any) => {
    return http
      .get(apis.getTreeByUser, {
        params: { organizationCode: value },
      })
      .then(res => {
        let data = res?.data?.children || []
        return data
      })
  }

  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }
}

interface IState extends IBaseListPageState {
  uploading: boolean
  downloading: boolean
  treeDataList: any[]
  prodBarCodeList: any[]
  loading?: boolean
}

interface IProps extends IBaseListPageProps { }
